import { authMiddleware } from '@/lib/api';
import { queryOauthClientByClientId, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import ResetPage from '@/app/[locale]/reset/reset';
import OauthAuthPage from '@/app/[locale]/oauth/auth/auth';
import type { IPath } from '@/interfaces';
import { notFound, redirect } from 'next/navigation';
import { customData, getMetadata } from '@/lib/tool';
import { nanoid } from 'nanoid';
import { Metadata as MetadataNext } from 'next';
import { createTranslator } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = createTranslator(await getMessages(locale));
  return getMetadata({ title: t('OauthPage.openAuthClient') });
}

export default async function Page({
  params = {},
  searchParams,
}: {
  params: {};
  searchParams: {
    response_type: string;
    responseType: string;
    client_id: string;
    clientId: string;
    redirect_uri: string;
    redirectUri: string;
    scope: string;
    state?: string;
  };
}) {
  if (
    typeof searchParams !== 'object' ||
    Object.keys(searchParams).length === 0
  ) {
    notFound();
  }

  try {
    const token = authMiddleware(cookies());
    const metadata = new Metadata();
    const user = await fetchUserData({ metadata, params, searchParams, token });
    if (!user.isLogin) {
      redirect(`/login?${new URLSearchParams(searchParams)}`);
    }

    metadata.set(
      'params',
      ['/oauth/clients/check', 'params'],
      customData({
        responseType: searchParams.response_type || searchParams.responseType,
        clientId: searchParams.client_id || searchParams.clientId,
        redirectUri: searchParams.redirect_uri || searchParams.redirectUri,
        scope: searchParams.scope,
        state: searchParams.state || nanoid(),
      }),
    );
    return <OauthAuthPage metadata={metadata.toString()} />;
  } catch (e) {
    return <ResetPage error={e} />;
  }
}

const fetchUserData = async ({
  metadata,
  params,
  searchParams,
  token,
}: {
  metadata: Metadata;
  params: {};
  searchParams: {
    client_id: string;
    clientId: string;
  };
  token: string | undefined;
}) => {
  try {
    const clientId = searchParams.client_id || searchParams.clientId;
    if (!clientId) {
      return {
        isLogin: false,
      };
    }

    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryOauthClientByClientId({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: clientId,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();
    const data = resp1.data as IPath;
    if (!data.user) {
      return {
        isLogin: false,
      };
    }

    metadata.set('page', ['/paths', '/'], resp1.data);
    metadata.set('client', ['/oauth', '/clients', clientId, '/by'], resp2.data);
    return {
      isLogin: true,
    };
  } catch (e) {
    return {
      isLogin: false,
    };
  }
};
